package com.wky.user.service.impl;

import com.wky.basic.Result.PageResult;
import com.wky.basic.constant.SmsContants;
import com.wky.basic.exception.BusinessException;
import com.wky.basic.service.impl.BaseServiceImpl;
import com.wky.basic.util.StrUtils;
import com.wky.org.mapper.DepartmentMapper;
import com.wky.org.mapper.EmployeeMapper;
import com.wky.org.pojo.Department;
import com.wky.org.pojo.Employee;
import com.wky.org.service.DepartmentService;
import com.wky.user.dto.RegisterDTO;
import com.wky.user.mapper.LoginInfoMapper;
import com.wky.user.mapper.UserMapper;
import com.wky.user.pojo.LoginInfo;
import com.wky.user.pojo.User;
import com.wky.user.service.LoginInfoService;
import com.wky.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class UserServicerImpl extends BaseServiceImpl<User> implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LoginInfoMapper loginInfoMapper;

    /**
     * 手机注册
     * @param registerDTO
     */
    @Override
    @Transactional
    public void phoneRegister(RegisterDTO registerDTO) {

        String phoneCode = registerDTO.getPhoneCode();
        String phone = registerDTO.getPhone();
        String password = registerDTO.getPassword();
        String rePassword = registerDTO.getRePassword();
        Integer type = registerDTO.getType();
        //1. 判断所有参数是否为空
        if (phoneCode == null || phone == null || password == null || rePassword == null) {
            throw new BusinessException("参数不能为空");
        }
        //2. 判断两次密码是否相同
        if (!password.equals(rePassword)) {
            throw new BusinessException("两次密码不一致");
        }
        //3. 判断手机验证码是否正确
        String key = String.format(SmsContants.VERIFY_CODE_KEY,phone);
        Map<String, String> value = (Map<String, String>) redisTemplate.opsForValue().get(key);
            //验证码过期
            if(value==null){
                throw new BusinessException("验证码已过期");
            }
            String code = value.get("code");
            //验证码错误
            if (!code.equals(phoneCode)){
                throw new BusinessException("验证码错误");
            }
        //4. 判断手机号是否被注册
            //1. 获取手机号
            User user = userMapper.findByPhone(phone);
            //根据phone和type查询loginInfo信息
            LoginInfo loginInfoDb = loginInfoMapper.findByPhoneAndType(phone,type);
            //情况一：user表存在记录，但登录信息表不存在记录
            if (user != null && user.getLogininfoId() == null && loginInfoDb == null) {
                //新增loginInfo表
                LoginInfo loginInfo = new LoginInfo();
                loginInfo.setUsername(phone);
                loginInfo.setPhone(phone);
                loginInfo.setPassword(password);
                loginInfo.setType(type);
                loginInfo.setDisable(1);
                loginInfoMapper.add(loginInfo);
                //更新user表
                user.setLogininfoId(loginInfo.getId());
                userMapper.update(user);
            }
            //情况二： user表存在记录，但登录信息表存在记录，但user表的loginInfoId字段为空
            if (user != null && user.getLogininfoId() == null && loginInfoDb != null) {
                user.setLogininfoId(loginInfoDb.getId());
                userMapper.update(user);

                loginInfoDb.setUsername(phone);
                loginInfoDb.setPhone(phone);
                loginInfoDb.setPassword(password);
                loginInfoDb.setType(type);
                loginInfoDb.setDisable(1);
                loginInfoMapper.update(loginInfoDb);
            }
            //情况三：user表不存在记录，但登录信息表存在记录
            if (user == null && loginInfoDb != null) {
                user = new User();
                user.setLogininfoId(loginInfoDb.getId());
                userMapper.add(user);

                loginInfoDb.setUsername(phone);
                loginInfoDb.setPhone(phone);
                loginInfoDb.setPassword(password);
                loginInfoDb.setType(type);
                loginInfoDb.setDisable(1);
                loginInfoMapper.update(loginInfoDb);
            }
            //情况四：user表与登录信息表都存在记录
            if (user != null && user.getLogininfoId() != null && loginInfoDb != null) {
                throw new BusinessException("手机号已注册");
            }
        //5. 添加用户和登录信息
        LoginInfo loginInfo = new LoginInfo();
            loginInfo.setUsername(phone);
            loginInfo.setPhone(phone);
            loginInfo.setPassword(password);
            loginInfo.setType(type);
            loginInfo.setDisable(1);
            loginInfoMapper.add(loginInfo);
        User user1 = new User();
            user1.setUsername(phone);
            user1.setLogininfoId(loginInfo.getId());
            user1.setPassword(password);
            user1.setCreatetime(new Date());
            userMapper.add(user1);
        //6. 删除redis中的验证码
        redisTemplate.delete(key);
    }

    /**
     * 邮箱注册
     * @param registerDTO
     */
    @Override
    @Transactional
    public void emailRegister(RegisterDTO registerDTO) {

        //1. 获取参数
        String email = registerDTO.getEmail();
        String emailCode = registerDTO.getEmailCode();
        String password = registerDTO.getPassword();
        String rePassword = registerDTO.getRePassword();
        Integer type = registerDTO.getType();
        //2. 判断所有参数是否为空
        if (email == null || password == null || rePassword == null) {
            throw new BusinessException("参数不能为空");
        }
        //3. 验证邮箱格式
        if (!email.matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$")) {
            throw new BusinessException("邮箱格式错误");
        }

        //4. 验证两次密码是否一致
        if (!password.equals(rePassword)) {
            throw new BusinessException("两次密码不一致");
        }

        //3. 判断邮箱验证码是否正确
        String key = String.format(SmsContants.EMAIL_VERIFY_CODE_KEY,email);
        Map<String, String> value = (Map<String, String>) redisTemplate.opsForValue().get(key);
            //验证码过期
            if(value==null){
                throw new BusinessException("验证码已过期");
            }
            String code = value.get("code");
            //验证码错误
            if (!code.equals(emailCode)){
                throw new BusinessException("验证码错误");
            }

        //5. 验证邮箱是否被注册
        User user = userMapper.findByEmail(email);
        if (user != null) {
            throw new BusinessException("邮箱已注册");
        }
        //6. 添加用户和登录信息
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setUsername(email);
        loginInfo.setEmail(email);
        loginInfo.setPassword(password);
        loginInfo.setType(type);
        loginInfo.setDisable(1);
        loginInfoMapper.add(loginInfo);

        User user1 = new User();
        user1.setUsername(email);
        user1.setLogininfoId(loginInfo.getId());
        user1.setPassword(password);
        user1.setCreatetime(new Date());
        user1.setEmail(email);
        userMapper.add(user1);
        //7. 删除redis中的验证码
        redisTemplate.delete(String.format(SmsContants.VERIFY_CODE_KEY,email));

    }
}
